﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TreeGrid
{
	public class TreeGridViewRow : DataGridViewRow
	{
		private TreeGridViewRow m_parentRow;
		private List<TreeGridViewRow> m_lstChildRow = new List<TreeGridViewRow>();
		private bool isExpand = false;

		public TreeGridViewRow()
		{
			IsExpand = true;
		}

		public int Layer
		{
			get
			{
				int layer = 0;

				TreeGridViewRow row = ParentRow;
				while (row != null)
				{
					layer++;
					row = row.ParentRow;
				}

				return layer;
			}
		}

		public TreeGridViewRow ParentRow
		{
			get => m_parentRow;
			set => m_parentRow = value;
		}

		public bool HasChildren
		{
			get
			{
				return m_lstChildRow.Count > 0;
			}
		}


		public TreeGridViewRow[] ChildRows
		{
			get
			{
				return m_lstChildRow.ToArray();
			}
		}

		public bool IsExpand
		{
			get { return isExpand; }
			set
			{
				isExpand = value;
				bool bShow = true;
				if (isExpand)
					bShow = true;
				else
					bShow = false;

				foreach (TreeGridViewRow row in m_lstChildRow)
				{
					row.SetVisible(bShow);
				}
			}
		}

		public bool IsParentLastChild
		{
			get
			{
				if (ParentRow != null)
				{
					return ParentRow.m_lstChildRow.Last() == this;
				}

				return false;
			}
		}

		private void SetVisible(bool bVisible)
		{
			this.Visible = bVisible;

			foreach (var r in m_lstChildRow)
			{
				if (bVisible && isExpand)
				{
					r.SetVisible(true);
				}
				else
				{
					r.SetVisible(false);
				}
			}
		}

		//public override bool Visible
		//{
		//	get
		//	{
		//		TreeGridViewRow parent = ParentRow;
		//		while (parent != null)
		//		{
		//			if (!parent.isExpand)
		//				return false;
		//		}

		//		return true;
		//	}
		//	set
		//	{
		//		//base.Visible = value;
		//	}
		//}

		public void AddChildRow(TreeGridViewRow row)
		{
			row.ParentRow = this;
			m_lstChildRow.Add(row);
			if (this.DataGridView != null)
				this.DataGridView.Rows.Add(row);
		}

		public void RemoveChildRow(TreeGridViewRow row)
		{
			row.ParentRow = null;
			m_lstChildRow.Remove(row);
		}

		public int ChildRowCount()
		{
			int iCount = m_lstChildRow.Count;
			foreach (var r in m_lstChildRow)
			{
				iCount += r.ChildRowCount();
			}

			return iCount;
		}
	}
}
